/**
 * 
 */
package com.android.zing;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.util.Log;

/**
 * @author trangdoan
 *
 */
public class ZME_Utils {

	
	/**
     * Display a simple alert dialog with the given text and title.
     *
     * @param context
     *          Android context in which the dialog should be displayed
     * @param title
     *          Alert dialog title
     * @param text
     *          Alert dialog message
     */
    public static void showAlert(Context context, String title, String text) {
        Builder alertBuilder = new Builder(context);
        alertBuilder.setTitle(title);
        alertBuilder.setMessage(text);
        alertBuilder.create().show();
    }
    
    /**
     * Parse a URL query and fragment parameters into a key-value bundle.
     *
     * @param url the URL to parse
     * @return a dictionary bundle of keys and values
     */
    public static Bundle parseUrl(String url) {
        // hack to prevent MalformedURLException
        url = url.replace("zmconnect", "http");
        try {
            URL u = new URL(url);
            Bundle b = decodeUrl(u.getQuery());
            Log.d("ZME_Utils", "after parseURL with Query : " + b);
            b.putAll(decodeUrl(u.getRef()));
            
            Log.d("ZME_Utils", "after parseUrl : " + b);
            return b;
        } catch (MalformedURLException e) {
        	Log.e("ZME_Utils", "got exception when parse URL");
        	e.printStackTrace();
            return new Bundle();
        }
    }
    
    public static String encodeUrl(Bundle parameters) {
        if (parameters == null) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (String key : parameters.keySet()) {
            if (first) first = false; else sb.append("&");
            sb.append(URLEncoder.encode(key) + "=" +
                      URLEncoder.encode(parameters.getString(key)));
        }
        return sb.toString();
    }

    public static Bundle decodeUrl(String s) {
    	Log.d("ZME_Utils", "query: " + s);
    	
        Bundle params = new Bundle();
        if (s != null) {
            String array[] = s.split("&");
            for (String parameter : array) {
                String v[] = parameter.split("=");
                params.putString(URLDecoder.decode(v[0]),
                                 URLDecoder.decode(v[1]));
            }
        }
        return params;
    }
    
    public static void clearCookies( Context ctx ) {
    	CookieSyncManager cookieSyncMngr =
    	            CookieSyncManager.createInstance(ctx);
    	
    	CookieManager cm = CookieManager.getInstance();
    	cm.removeAllCookie();
    }
}
